package com.xiaoc.bulldozer.common.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import net.minidev.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * describe:
 *
 * @author lihuancheng
 * @date 2018/9/7
 */
public class JwtUtil {

    private static byte[] SECRET = "Lku4rml6XlpLgtertrml6XlTm456erCJuY@naEiLCJuY@@@@!!!".getBytes();

    /**
     * 生成 JWT token
     * @return
     * @throws JOSEException
     */
    public static String creatToken() throws JOSEException {


        Map<String, Object> payloadMap = new HashMap<>();
        long currentTime = System.currentTimeMillis();
        payloadMap.put("iss", "cxet");
        // 过期时间
        payloadMap.put("exp", currentTime / 1000 + 3600*6);
        payloadMap.put("nbf", currentTime / 1000 );

        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256);

        //建立一个载荷Payload
        Payload payload = new Payload(new JSONObject(payloadMap));

        //将头部和载荷结合在一起
        JWSObject jwsObject = new JWSObject(jwsHeader, payload);

        //建立一个密匙
        JWSSigner jwsSigner = new MACSigner(SECRET);

        //签名
        jwsObject.sign(jwsSigner);

        //生成token
        return jwsObject.serialize();
    }



}
